<?php

namespace App\Modules\Apicrzs\Services\Users;

use App\Exceptions\ApiException;
use App\Exceptions\Exception;
use App\Modules\Admin\Entities\Member\UserAddressModel;
use App\Modules\Admin\Entities\Member\UserExtractModel;
use App\Modules\Apicrzs\Services\BaseServices;
use App\Traits\CryptAES;
use Illuminate\Support\Facades\DB;

class UserAddressService extends BaseServices
{

    public function __construct( UserAddressModel $model)
    {
        $this->model = $model;

        $token =  \request()->header('token');
        $user_info = CryptAES::decryptToken($token,'user_grzq');
//
        $this->user_id = $user_info['data']['user_id']??"";
        $this->model = $model;
    }
    public function getLists($params){


        $where['user_id'] = $this->user_id;
        $where['is_delete'] =0;
        $model = $this->model->where($where);

        $lists = $model->orderBy('created_time', 'DESC')
            ->paginate($this->getLimit($params['limit'] ?? 10));

        return [
            'current_page' => $lists->currentPage(),
            'per_page'     => $lists->perPage(),
            'count_page'   => $lists->lastPage(),
            'total'        => $lists->total(),
            'data'         => $lists->items(),
        ];
    }
    public function create(array $params)
    {
        DB::beginTransaction();
        try{
            if ($params['is_default']==1){
                $this->model->where(['user_id'=>$this->user_id])->update(['is_default' => 0]);
            }
            $params['user_id'] = $this->user_id;
            $this->detail = parent::create($params); // TODO: Change the autogenerated stub
            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new ApiException($e->getMessage());
        }
    }

    public function update(array $params)
    {
        DB::beginTransaction();
        try{
            if ($params['is_default']==1){
                $this->model->where(['user_id'=>$this->user_id])->update(['is_default' => 0]);
            }
            $params['user_id'] = $this->user_id;
            parent::update($params); // TODO: Change the autogenerated stub
            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new ApiException($e->getMessage());
        }
    }
    public function setDefault($params)
    {
        $address_id = $params['id'];
        $this->model->where(['user_id'=>$this->user_id])->update(['is_default' => 0]);
        $this->update(['id'=>$address_id,'is_default'=>1]);
        $this->error = '修改默认地址成功';
        return true;
    }
    public function setDel($params)
    {
        $address_id = $params['id'];
        $this->model->where(['id'=>$address_id])->update(['id'=>$address_id,'is_delete'=>1]);
        $this->error = '删除成功';
        return true;
    }
}
